#include "ringqueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <cstdio>
using namespace std;


pthread_mutex_t CoutMtx;
string SelfName()
{
    char name[1024];
    snprintf(name,sizeof name, "%thread[0x%x]",pthread_self());
    return name;
}


void* Productor_startroute(void* rq)
{
    //RingQueue<int>* ringqueue = static_cast<RingQueue<int>*>(rq); 
    RingQueue<Task>* ringqueue = static_cast<RingQueue<Task>*>(rq); 
    while(1)
    {
        //int data = rand() % 10 + 1;
        int x = rand() % 10 + 1;
        int y = rand() % 5;
        char op = oper[rand()%oper.size()];
        Task t(x,y,op);
        //ringqueue->push(data);
        ringqueue->push(t);
        pthread_mutex_lock(&CoutMtx);
        //cout << SelfName() << ":" << "我正在生产任务:" << t.to_TaskString() << endl;
        cout << "我正在生产任务:" << t.to_TaskString() << endl;
        pthread_mutex_unlock(&CoutMtx);
        sleep(1);
    }

    return nullptr;
}

void* Cosummer_startroute(void* rq)
{
    //RingQueue<int>* ringqueue = static_cast<RingQueue<int>*>(rq); 
    RingQueue<Task>* ringqueue = static_cast<RingQueue<Task>*>(rq); 
    while(1)
    {
        Task t;
        //ringqueue->pop(&data);
        ringqueue->pop(&t);
        pthread_mutex_lock(&CoutMtx);
        //cout << SelfName() << "我正在消费任务:" << data << endl;
        cout << "我正在消费任务:" << t() << endl;
        pthread_mutex_unlock(&CoutMtx);
        sleep(1);
    }    

    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr));
    //RingQueue<int>* rq = new RingQueue<int>();
    RingQueue<Task>* rq = new RingQueue<Task>();
    pthread_mutex_init(&CoutMtx,nullptr);
    

    // //多生产多消费
    // vector<pthread_t> Pv;
    // Pv.resize(4);
    // vector<pthread_t> Cv;
    // Cv.resize(8);
    // for(int i = 0; i < Pv.size(); i++)
    // {
    //     pthread_create(&Pv[i],nullptr,Productor_startroute,rq);
    // }
    // for(int i = 0; i < Cv.size(); i++)
    // {
    //     pthread_create(&Cv[i],nullptr,Cosummer_startroute,rq);
    // }

    // for(int i = 0; i < Pv.size(); i++)
    // {
    //     pthread_join(Pv[i],nullptr);
    // }
    // for(int i = 0; i < Cv.size(); i++)
    // {
    //     pthread_join(Cv[i],nullptr);
    // }


    //单生产单消费
    pthread_t p,c;
    pthread_create(&p,nullptr,Productor_startroute,rq);
    pthread_create(&c,nullptr,Cosummer_startroute,rq);

    pthread_join(p,nullptr);
    pthread_join(c,nullptr);


    pthread_mutex_destroy(&CoutMtx);
    delete rq;

    return 0;
}